package com.letianpai.activity.homeland;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.letianpai.R;
import com.letianpai.adapter.homeland.MemListAdapter;
import com.letianpai.bean.homeland.FriendListHome;
import com.letianpai.common.server.ResultBean;
import com.letianpai.common.server.ServerInterface;
import com.letianpai.common.server.ServerTool;
import com.letianpai.db.Constant;
import com.letianpai.http.homeland.JoinHoemlandBean;
import com.letianpai.http.homeland.JoinHomelandRequest;
import com.letianpai.utils.ChatUtils;
import com.letianpai.utils.JsonUtil;
import com.letianpai.utils.Utils;
import com.letianpai.utils.XmppTool;

public class AddMActivity extends Activity {
    private Roster roster;
    ArrayList<FriendListHome> arraylist;
    ListView listview;
    TextView headText, add_button_homeland;
    String title;
    String signId, name = "", username;
    RequestQueue requestQueue;
    ProgressDialog pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.add_m);
        initView();
    }

    private void initView() {
        requestQueue = Volley.newRequestQueue(this);

        signId = getIntent().getStringExtra("signId");
        username = getIntent().getStringExtra("username");
        add_button_homeland = (TextView) findViewById(R.id.add_button_homeland);
        add_button_homeland.setOnClickListener(new MClick());
        headText = (TextView) findViewById(R.id.headText);
        title = getIntent().getStringExtra("title");
        headText.setText(title);
        Log.d("zzzz", title+"title");
        listview = (ListView) findViewById(R.id.listView);
        arraylist = new ArrayList<FriendListHome>();
        if ("添加成员".equals(title)) {
        	Log.d("zzzz", "添加成员"+"dialog");
            pd = new ProgressDialog(AddMActivity.this);
            Log.d("zzzz", pd.toString());
            pd.setTitle("请稍等");
            pd.setMessage("正在加载...");
            pd.show();
            pd.setCanceledOnTouchOutside(false);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // 登录openfire
					roster = XmppTool.con.getRoster();
					handler.sendEmptyMessage(1);
                }
            }).start();
        } else if ("移除成员".equals(title)) {
            getMemPost();
        }

    }

    public void familyList() {
        Collection<RosterEntry> groups = roster.getEntries();
        Log.d("zzzz", roster.toString());
        // 好友列表
        for (RosterEntry entry : groups) {
            if ("both".equals(entry.getType().name())) {// 只添加双边好友
                FriendListHome friendInfo = new FriendListHome();
                friendInfo.setUsername(Utils.getJidToUsername(entry.getUser()));
                String nick = ChatUtils.getname(
                        Utils.getJidToUsername(entry.getUser()));
                if (nick == null) {
                    friendInfo.setNickname(entry.getName());
                } else {
                    friendInfo.setNickname(nick);
                }
                try {
                    Bitmap mp = ChatUtils.getUserImage(Utils
                            .getJidToUsername(entry.getUser()));
                    friendInfo.setPic(mp);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                arraylist.add(friendInfo);
            }
        }
        Log.d("zzzz", arraylist.size() + "");
        MemListAdapter ml = new MemListAdapter(this, arraylist, new MClick());
        listview.setAdapter(ml);
    }

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    familyList();
                    pd.cancel();
                    break;

                default:
                    break;
            }
        }
    };

    class MClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.add_button_homeland:
                    if ("添加成员".equals(title)) {
                        getCheck();
                        pd = new ProgressDialog(AddMActivity.this);
                        pd.setTitle("请稍等");
                        pd.setMessage("正在添加...");
                        pd.show();
                        pd.setCanceledOnTouchOutside(false);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                addPost();
                            }
                        }).start();
                    } else if ("移除成员".equals(title)) {
                        getCheck();
                        pd = new ProgressDialog(AddMActivity.this);
                        pd.setTitle("请稍等");
                        pd.setMessage("正在移除...");
                        pd.show();
                        pd.setCanceledOnTouchOutside(false);
                        new Thread(new Runnable() {

                            @Override
                            public void run() {
                                quitPost();
                            }
                        }).start();
                    }
                    break;
                case R.id.checkBox_homeland:
                    arraylist.get((Integer) v.getTag()).setCheck(
                            !arraylist.get((Integer) v.getTag()).isCheck());
                    break;
                default:
                    break;
            }
        }

    }

    // 获取邀请的好友
    public ArrayList<FriendListHome> getCheck() {
        ArrayList<FriendListHome> list = new ArrayList<FriendListHome>();
        for (FriendListHome fl : arraylist) {
            if (fl.isCheck() == true) {
                list.add(fl);
                name += fl.getUsername() + ",";
            }
        }
        return list;
    }

    // 邀请成员
    public void addPost() {
        JoinHoemlandBean userInfo = new JoinHoemlandBean();
        JoinHomelandRequest user = new JoinHomelandRequest();
        userInfo.setAction("join");
        userInfo.setRoomid(signId);
        userInfo.setUsername(name);
        user.setHead("roomServlet");
        user.setContent(userInfo);
        String msg = JsonUtil.objectToString(user, JoinHomelandRequest.class);
        String url = Constant.URL + "?msg=" + msg;
        Log.d("zzzz", url + "聊天室");
        StringRequest request = new StringRequest(url, new Listener<String>() {

            @Override
            public void onResponse(String arg0) {
                pd.cancel();

                Log.d("zzzz", arg0);

                JSONTokener jsonParser = new JSONTokener(arg0);
                JSONObject person;
                String a = "";
                try {
                    person = (JSONObject) jsonParser.nextValue();
                    Log.d("zzzz", person.getString("status"));
                    a = person.getString("status");
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (a.equals("SUCCESS")) {
                    finish();
                    Toast.makeText(AddMActivity.this, "添加成功", Toast.LENGTH_LONG)
                            .show();
                } else {
                    Toast.makeText(AddMActivity.this, "添加失败", Toast.LENGTH_LONG)
                            .show();
                }

            }
        }, new ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
                pd.cancel();
                Toast.makeText(AddMActivity.this, "请求失败", Toast.LENGTH_LONG)
                        .show();
            }
        });
        requestQueue.add(request);
    }

    public void getMemPost() {
        Map<String, String> maps = new HashMap<String, String>();
        maps.put("action", "get");
        maps.put("roomid", signId);
        maps.put("username", username);
        ServerTool.getInstance().methodPost(AddMActivity.this, "roomMembersServlet", maps, new ContactRealize());
    }

    class ContactRealize implements ServerInterface {

        @Override
        public void gainData(ResultBean bean) {
            if (bean.isSuccess()) {
                arraylist = new ArrayList<FriendListHome>();
                try {

                    JSONObject parentObj = new JSONObject(bean.getResultContent());
                    String static_url = parentObj.getString("static_url");
                    JSONArray childArray = parentObj.getJSONArray("member_list");
                    int count = childArray.length();
                    for (int i = 0; i < count; i++) {
                        JSONObject childObj = childArray.getJSONObject(i);
                        FriendListHome member = new FriendListHome();
                        member.setUsername(childObj.getString("username"));
                        member.setNickname(childObj.getString("nickname"));
                        arraylist.add(member);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                MemListAdapter ml = new MemListAdapter(AddMActivity.this,
                        arraylist, new MClick());
                listview.setAdapter(ml);

            }
        }
    }

    public void quitPost() {
        JoinHoemlandBean userInfo = new JoinHoemlandBean();
        JoinHomelandRequest user = new JoinHomelandRequest();
        userInfo.setAction("quit");
        userInfo.setRoomid(signId);
        userInfo.setUsername(name);
        user.setHead("roomServlet");
        user.setContent(userInfo);
        String msg = JsonUtil.objectToString(user, JoinHomelandRequest.class);
        String url = Constant.URL + "?msg=" + msg;
        StringRequest request = new StringRequest(url, new Listener<String>() {

            @Override
            public void onResponse(String arg0) {
                pd.cancel();
                Log.d("zzzz", arg0);

                JSONTokener jsonParser = new JSONTokener(arg0);
                JSONObject person;
                String a = "";
                try {
                    person = (JSONObject) jsonParser.nextValue();
                    Log.d("zzzz", person.getString("status"));
                    a = person.getString("status");
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (a.equals("SUCCESS")) {
                    Toast.makeText(AddMActivity.this, "移除成功", Toast.LENGTH_LONG)
                            .show();
                    finish();
                } else {
                    Toast.makeText(AddMActivity.this, "移除失败", Toast.LENGTH_LONG)
                            .show();
                }
            }
        }, new ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
            	pd.cancel();
                Toast.makeText(AddMActivity.this, "请求失败", Toast.LENGTH_LONG)
                        .show();
            }
        });
        requestQueue.add(request);
    }
}
